
package com.ymx.sdk.widget.recyclerview;

import com.ymx.sdk.R;
import com.ymx.sdk.util.ViewUtils;
import com.ymx.sdk.widget.PullToRefreshView.LoadingLayoutProxy;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshBase;
import com.ymx.sdk.widget.PullToRefreshView.internal.LoadingLayout;
import com.ymx.sdk.widget.recyclerview.adapterItemAnimator.BaseAnimationAdapter;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

public class AutoPullToRefreshRecyclerView extends AutoPullToRefreshRecyclerViewBase<RecyclerView> {

    private LoadingLayout mHeaderLoadingView;
    private LoadingLayout mFooterLoadingView;
    private FrameLayout frame;
    private FrameLayout mLvFooterLoadingFrame;
    private boolean mListViewExtrasEnabled;

    public AutoPullToRefreshRecyclerView(Context context) {
        super(context);
    }

    public AutoPullToRefreshRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoPullToRefreshRecyclerView(Context context, Mode mode) {
        super(context, mode);
    }

    public AutoPullToRefreshRecyclerView(Context context, Mode mode, AnimationStyle style) {
        super(context, mode, style);
    }

    @Override
    public final Orientation getPullToRefreshScrollDirection() {
        return Orientation.VERTICAL;
    }

    @Override
    protected void onRefreshing(final boolean doScroll) {
        /**
         * If we're not showing the Refreshing view, or the list is empty, the
         * the header/footer views won't show so we use the normal method.
         */
        HFListRecyclerAdapter adapter = ViewUtils.getAdapter(mRefreshableView);
        if (!mListViewExtrasEnabled || !getShowViewWhileRefreshing() || null == adapter
                || adapter.getItemCount() == 0) {
            super.onRefreshing(doScroll);
            return;
        }

        super.onRefreshing(false);

        final LoadingLayout origLoadingView, listViewLoadingView, oppositeListViewLoadingView;
        final int selection, scrollToY;

        switch (getCurrentMode()) {
            case MANUAL_REFRESH_ONLY:
            case PULL_FROM_END:
                origLoadingView = getFooterLayout();
                listViewLoadingView = mFooterLoadingView;
                oppositeListViewLoadingView = mHeaderLoadingView;
                selection = mRefreshableView.getLayoutManager().getItemCount() - 1;
                scrollToY = getScrollY() - getFooterSize();
                break;
            case PULL_FROM_START:
            default:
                origLoadingView = getHeaderLayout();
                listViewLoadingView = mHeaderLoadingView;
                oppositeListViewLoadingView = mFooterLoadingView;
                selection = 0;
                scrollToY = getScrollY() + getHeaderSize();
                break;
        }

        // Hide our original Loading View
        origLoadingView.reset();
        origLoadingView.hideAllViews();

        // Make sure the opposite end is hidden too
        oppositeListViewLoadingView.setVisibility(View.GONE);

        // Show the ListView Loading View and set it to refresh.
        listViewLoadingView.setVisibility(View.VISIBLE);
        listViewLoadingView.refreshing();

        if (doScroll) {
            // We need to disable the automatic visibility changes for now
            disableLoadingLayoutVisibilityChanges();

            // We scroll slightly so that the ListView's header/footer is at the
            // same Y position as our normal header/footer
            setHeaderScroll(scrollToY);

            // Make sure the ListView is scrolled to show the loading
            // header/footer
            mRefreshableView.getLayoutManager().scrollToPosition(selection);

            // Smooth scroll as normal
            smoothScrollTo(0);
        }
    }

    public void addFrontView(boolean isAddFront) {
        addFrontFooterView(isAddFront);
    }

    @Override
    protected void onReset() {
        /**
         * If the extras are not enabled, just call up to super and return.
         */
        if (!mListViewExtrasEnabled) {
            super.onReset();
            return;
        }

        final LoadingLayout originalLoadingLayout, listViewLoadingLayout;
        final int scrollToHeight, selection;
        final boolean scrollLvToEdge;

        switch (getCurrentMode()) {
            case MANUAL_REFRESH_ONLY:
            case PULL_FROM_END:
                originalLoadingLayout = getFooterLayout();
                listViewLoadingLayout = mFooterLoadingView;
                selection = mRefreshableView.getLayoutManager().getItemCount() - 1;
                scrollToHeight = getFooterSize();
                scrollLvToEdge = Math.abs(((LinearLayoutManager) mRefreshableView
                        .getLayoutManager()).findLastVisibleItemPosition() - selection) <= 1;
                break;
            case PULL_FROM_START:
            default:
                originalLoadingLayout = getHeaderLayout();
                listViewLoadingLayout = mHeaderLoadingView;
                scrollToHeight = -getHeaderSize();
                selection = 0;
                scrollLvToEdge = Math.abs(((LinearLayoutManager) mRefreshableView
                        .getLayoutManager()).findFirstVisibleItemPosition() - selection) <= 1;
                break;
        }

        // If the ListView header loading layout is showing, then we need to
        // flip so that the original one is showing instead
        if (listViewLoadingLayout.getVisibility() == View.VISIBLE) {

            // Set our Original View to Visible
            originalLoadingLayout.showInvisibleViews();

            // Hide the ListView Header/Footer
            listViewLoadingLayout.setVisibility(View.GONE);

            /**
             * Scroll so the View is at the same Y as the ListView
             * header/footer, but only scroll if: we've pulled to refresh, it's
             * positioned correctly
             */
            if (scrollLvToEdge && getState() != State.MANUAL_REFRESHING) {
                mRefreshableView.getLayoutManager().scrollToPosition(selection);
                setHeaderScroll(scrollToHeight);
            }
        }

        // Finally, call up to super
        super.onReset();
    }

    @Override
    protected LoadingLayoutProxy createLoadingLayoutProxy(final boolean includeStart,
            final boolean includeEnd) {
        LoadingLayoutProxy proxy = super.createLoadingLayoutProxy(includeStart, includeEnd);

        if (mListViewExtrasEnabled) {
            final Mode mode = getMode();

            if (includeStart && mode.showHeaderLoadingLayout()) {
                proxy.addLayout(mHeaderLoadingView);
            }
            if (includeEnd && mode.showFooterLoadingLayout()) {
                proxy.addLayout(mFooterLoadingView);
            }
        }

        return proxy;
    }

    protected RecyclerView createRecyclerView(Context context, AttributeSet attrs) {
        return new InternaRecyclerView(context, attrs);
    }

    @Override
    protected RecyclerView createRefreshableView(Context context, AttributeSet attrs) {
        RecyclerView lv = createRecyclerView(context, attrs);
        return lv;
    }

    @Override
    protected void handleStyledAttributes(TypedArray a) {
        super.handleStyledAttributes(a);
        mListViewExtrasEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrListViewExtrasEnabled,
                true);
        if (mListViewExtrasEnabled) {
            final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);

            // Create Loading Views ready for use later
            frame = new FrameLayout(getContext());
            mHeaderLoadingView = createLoadingLayout(getContext(), Mode.PULL_FROM_START, a);
            mHeaderLoadingView.setVisibility(View.GONE);
            frame.addView(mHeaderLoadingView, lp);

            mLvFooterLoadingFrame = new FrameLayout(getContext());
            mFooterLoadingView = createLoadingLayout(getContext(), Mode.PULL_FROM_END, a);
            mFooterLoadingView.setVisibility(View.GONE);
            mLvFooterLoadingFrame.addView(mFooterLoadingView, lp);

            /**
             * If the value for Scrolling While Refreshing hasn't been
             * explicitly set via XML, enable Scrolling While Refreshing.
             */
            if (!a.hasValue(R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled)) {
                setScrollingWhileRefreshingEnabled(true);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        /**
         * This is a bit hacky, but Samsung's ListView has got a bug in it when
         * using Header/Footer Views and the list is empty. This masks the issue
         * so that it doesn't cause an FC. See Issue #66.
         */
        try {
            return super.dispatchTouchEvent(ev);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            return false;
        }
    }

    protected class InternaRecyclerView extends RecyclerView {

        private boolean mAddedLvFooter = false;

        public InternaRecyclerView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            /**
             * This is a bit hacky, but Samsung's ListView has got a bug in it
             * when using Header/Footer Views and the list is empty. This masks
             * the issue so that it doesn't cause an FC. See Issue #66.
             */
            try {
                super.dispatchDraw(canvas);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            /**
             * This is a bit hacky, but Samsung's ListView has got a bug in it
             * when using Header/Footer Views and the list is empty. This masks
             * the issue so that it doesn't cause an FC. See Issue #66.
             */
            try {
                return super.dispatchTouchEvent(ev);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
                return false;
            }
        }

        public void setAdapter(HFListRecyclerAdapter adapter) {

            // Add the Footer View at the last possible moment
            if (null != mLvFooterLoadingFrame && !mAddedLvFooter) {
                ViewUtils.getAdapter(mRefreshableView).addFooterView(mLvFooterLoadingFrame);
                mAddedLvFooter = true;
            }
            super.setAdapter(adapter);
        }

    }

    /**
     * notice:{@link HFListRecyclerAdapter#addHeaderView} before setAdapter
     * Pass-through method for {@link PullToRefreshBase#getRefreshableView()
     * getRefreshableView()}. This is just for convenience!
     *
     * @param adapter - Adapter to set
     */
    public void setAdapter(@NonNull HFListRecyclerAdapter adapter) {
        adapter.addHeaderView(frame);
        super.setAdapter(adapter);
    }

    /**
     * recyclerview with Animation
     *
     * @param adapter
     */
    public void setAdapter(@NonNull BaseAnimationAdapter adapter) {
        if (adapter.getWrappedAdapter() instanceof HFListRecyclerAdapter) {
            ((HFListRecyclerAdapter) adapter.getWrappedAdapter()).addHeaderView(frame);
        } else {
            throw new IllegalArgumentException("You Need HFListRecyclerAdapter!");
        }
        super.setAdapter(adapter);
    }
}
